package com.dolphin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.dolphin.commons.Pager;
import com.dolphin.mapper.RoleMapper;
import com.dolphin.model.Role;
import com.dolphin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 获取角色列表(不分页)
     *
     * @return List<Role>
     */
    @Transactional(readOnly = true)
    public List<Role> getRoleList() {
        return roleMapper.list(null);
    }

    public Pager<Role> list(Pager<Role> pager) {
        PageHelper.startPage(pager.getPageIndex(), pager.getPageSize());
        QueryWrapper<Role> userQueryWrapper = new QueryWrapper<>(pager.getForm());
        List<Role> categories = this.list(userQueryWrapper);
        PageInfo<Role> pageInfo = new PageInfo<>(categories);
        pager.setTotal(pageInfo.getTotal());
        pager.setData(pageInfo.getList());
        pager.setCode(Pager.SUCCESS_CODE);
        return pager;
    }

    /**
     * 根据角色代码获取角色
     *
     * @param roleCode 角色代码
     * @return Role
     */
    @Transactional(readOnly = true)
    public Role getRoleByCode(String roleCode) {
        return roleMapper.getRoleByCode(roleCode);
    }

    /**
     * 根据角色代码获取角色
     *
     * @param id 角色代码
     * @return Role
     */
    @Transactional(readOnly = true)
    public Role getRoleById(Long id) {
        return roleMapper.getRoleById(id);
    }

    @Override
    public int add(Role role) {
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        return roleMapper.add(role);
    }
}
